package com.example.sharesinfo.fragment.search;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.bean.SearchStocksBean;
import com.example.sharesinfo.db.WordHistory;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.LitePalHelper;
import com.example.sharesinfo.model.ChatRecordModel;
import com.example.sharesinfo.model.SearchStockModel;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询记得替换id
 */
public class SearchStockFragment extends Fragment {
    private static final int GetStartSearchStocksSuccess = 1001;
    private static final int GetStartSearchStocksFailed = 1002;
    private GridView mGvHistory;
    private SimpleAdapter adapter;
    private List<Map<String, Object>> history;
    private TextView tv_clear;
    private TextView stock_name_1;
    private TextView stock_name_2;
    private TextView stock_name_3;
    private TextView stock_name_4;
    public LinearLayout stock_start;
    public TextView title;
    //搜索结果
    public RecyclerView mStockView;
    public CommonAdapter<SearchStockModel> mStockAdapter;
    public List<SearchStockModel> mList = new ArrayList<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GetStartSearchStocksSuccess:
                    SearchStocksBean result = (SearchStocksBean) msg.obj;
                    List<SearchStockModel> MySearch = result.getMySearch();
                    List<SearchStockModel> AllSearch = result.getAllSearch();
                    stock_name_1.setText(AllSearch.get(0).getStockName());
                    stock_name_2.setText(AllSearch.get(1).getStockName());
                    stock_name_3.setText(AllSearch.get(2).getStockName());
                    stock_name_4.setText(AllSearch.get(3).getStockName());
                    initGvHistory(MySearch);
                    break;
                case GetStartSearchStocksFailed:
                    Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_search_stock, null);
        initView(view);
        getStartSearchStocks();
        return view;
    }


    private void initView(View view) {
        title = view.findViewById(R.id.title);
        stock_start = view.findViewById(R.id.stock_start);
        mGvHistory = view.findViewById(R.id.gv_history);
        stock_name_1 = view.findViewById(R.id.stock_name_1);
        stock_name_2 = view.findViewById(R.id.stock_name_2);
        stock_name_3 = view.findViewById(R.id.stock_name_3);
        stock_name_4 = view.findViewById(R.id.stock_name_4);
        tv_clear = view.findViewById(R.id.tv_clear);
        mStockView = view.findViewById(R.id.stock_search);
        mStockView.setLayoutManager(new LinearLayoutManager(getContext()));
        mStockView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL));
        mStockAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<SearchStockModel>() {
            @Override
            public void onBindViewHolder(final SearchStockModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.stock_name, model.getStockName());
                viewHolder.setText(R.id.stock_code, model.getStockCode());
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharesInfoActivity.startActivity(getContext(), model.getStockCode());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.activity_search_stock_item;
            }
        });
        mStockView.setAdapter(mStockAdapter);
    }

    private void getStartSearchStocks() {
        String url = "http://119.23.221.142/api/stock/GetStartSearchStocks?UserId=10";
        // + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                Message message = mHandler.obtainMessage();
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    SearchStocksBean bean = new Gson().fromJson(s, SearchStocksBean.class);
                    message.what = GetStartSearchStocksSuccess;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetStartSearchStocksFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    /**
     * 初始化数据
     *
     * @param mySearch
     */
    private void initGvHistory(List<SearchStockModel> mySearch) {
        if (CommonUtils.isEmpty(mySearch)) {
            tv_clear.setTag("unempty");
            tv_clear.setText("清楚历史记录");
            String[] from = {"text"};
            int[] to = {R.id.tv_word};
            history = new ArrayList<>();
            for (int i = 0; i < mySearch.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("text", mySearch.get(i).getStockName());
                map.put("code", mySearch.get(i).getStockCode());
                history.add(map);
            }
            adapter = new SimpleAdapter(getContext(), history, R.layout.layout_word_search_item, from, to);
            mGvHistory.setAdapter(adapter);
            mGvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(getContext(), history.get(position).get("text").toString() + history.get(position).get("code").toString(), Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            //
            tv_clear.setTag("empty");
            tv_clear.setText("暂无搜索历史");
        }
    }
}
